package cn.youyeku.zsxh.ui.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.youyeku.zsxh.R;
import cn.youyeku.zsxh.Utils.AppConfig;
import cn.youyeku.zsxh.Utils.LogUtils;
import cn.youyeku.zsxh.Utils.StringUtils;
import cn.youyeku.zsxh.adapter.ChatAdapter;
import cn.youyeku.zsxh.api.XhApi;
import cn.youyeku.zsxh.app;
import cn.youyeku.zsxh.bean.Msg;
import cn.youyeku.zsxh.bean.MsgList;
import cn.youyeku.zsxh.common.Contanst;
import cn.youyeku.zsxh.db.YeDBConnect;
import cn.youyeku.zsxh.service.MessageType;
import cn.youyeku.zsxh.ui.UIControl;
import cn.youyeku.zsxh.ui.activity.ABS.HandleActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 聊天界面,使用recyclerview实现
 */
public class PrivateMessage extends HandleActivity implements MessageType {
    private RecyclerView recyclerview;
    private EditText et_input;
    private List<Msg> mMsgList = new ArrayList<>();
    private ChatAdapter mMsgAdapter;

    private YeDBConnect db;

    //uid server要引用
    public static String uid ;


    private String addToDataBase = "insert into `%s` (sender_id,message_content,send_time,message_status,message_type) VALUES(%s,'%s','%s',%s,%s)";
    private String selectDatabase = "select send_time,message_content,message_type,sender_id from `%s` where  sender_id=%s ORDER BY send_time ASC";
    private Cursor cursor;
    private MyReceiver receiver;
    private String title;
    private String content;

    @Override
    protected void onChange() {
        mMsgList.add(new Msg(content, MESSAGE_TYPE_ME,StringUtils.getNowDate()));
        insertDataBase(content);
        // 通知数据适配器刷新界面
        mMsgAdapter.notifyDataSetChanged();
        // 定位到最后一行
        recyclerview.scrollToPosition(mMsgList.size() - 1);
        // 输入框置空
        et_input.setText("");
    }

    @Override
    protected void onError() {

    }

    @Override
    protected void onSuccess() {
        mMsgAdapter.add(mMsgList);
        // 定位到最后一行
        recyclerview.scrollToPosition(mMsgList.size() - 1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initActionBar();


        if (savedInstanceState != null) {
            uid = savedInstanceState.getString("uid");
            title = savedInstanceState.getString("title");
        } else {
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            uid = bundle.getString("uid");
            title = bundle.getString("title");

        }
        setTitle(title);



        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        et_input = (EditText) findViewById(R.id.et_input);
        Button bt_send = (Button) findViewById(R.id.bt_send);
//        Button bt_send2 = (Button) findViewById(R.id.bt_send2);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);

        mMsgList = new ArrayList<>();

        initUser();


        mMsgAdapter = new ChatAdapter(mMsgList);
        recyclerview.setAdapter(mMsgAdapter);


        bt_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               content = et_input.getText().toString().trim();
                // 如果用户没有输入,则是一个空串""
                if (!content.isEmpty()) {
                    XhApi.send_private_message(uid, content, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            try {
                                String data = response.body().string();
                                JSONObject object = new JSONObject(data);
                                LogUtils.w(data);
                                int code = object.getInt("code");
                                String message = object.getString("message");
                                if(code == 200){
                                    Message msg = new Message();
                                    msg.what =CHANGE_MESSAGE;
                                    handler.sendMessage(msg);

                                    app.backgroundThreadShortToast(message);
                                }else{
                                    app.backgroundThreadShortToast(message);
                                }



                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });

                }else {
                    app.backgroundThreadShortToast("输入内容为空");
                }
            }
        });




        //注册广播接收器
        receiver=new MyReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("cn.youyeku.zsxh.service");
        this.registerReceiver(receiver,filter);

    }
    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

//            对数据处理
            Bundle bundle=intent.getExtras();
            String content = bundle.getString("content");
            String time = bundle.getString("time");
            addFriends(content,time);


        }
    }

    private void initUser() {


        db = YeDBConnect.getInstance(getApplicationContext(), 'w');
        Contanst.ON_CHAT =true;
        Contanst.CHAT_USER_ID=uid;

        new Thread(new Runnable() {
            @Override
            public void run() {
                cursor = db.executeFetchData(String.format(selectDatabase,AppConfig.CONF_USER_ID,uid));

                while (cursor.moveToNext()) {
                    String sender_time = cursor.getString(0);
                    String message_content = cursor.getString(1);
                    int message_type = cursor.getInt(2);
                    mMsgList.add(new Msg(message_content,message_type,sender_time));

                }
                LogUtils.w("获取数据库完成");
                Message msg = new Message();
                msg.what=STATUS_SUCCESS;
                handler.sendMessage(msg);
            }
        }).start();


    }


    public  void addFriends(String content,String time){
        mMsgList.add(new Msg(content, MESSAGE_TYPE_FRIEND,time));
        // 通知数据适配器刷新界面
        mMsgAdapter.notifyDataSetChanged();
        // 定位到最后一行
        recyclerview.scrollToPosition(mMsgList.size() - 1);
    }
    private void insertDataBase(String content) {
//        insert into msg (sender_id,message_content,send_time,message_status,message_type) value(%s,'%s','%s',%s,%s)
        LogUtils.w(StringUtils.getNowDate());
        db.execute(String.format(addToDataBase, AppConfig.CONF_USER_ID,uid, content, StringUtils.getNowDate(), MESSAGE_READ, MESSAGE_TYPE_ME));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Contanst.ON_CHAT =false;
        this.unregisterReceiver(receiver);
        LogUtils.w("销毁");
    }



}